<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class ClothmakingOutstock extends Model
{





    // 表名
    protected $name = 'clothmaking_outstock';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'out_type_text'
    ];



    public function getStatusList()
    {
        return ['nomarl' => __('Nomarl'), 'checked' => __('Checked'), 'completed' => __('Completed')];
    }

    public function getOutTypeList()
    {
        return ['sale' => __('Sale'), 'return' => '报废', 'other' => __('Other')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getOutTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['out_type']) ? $data['out_type'] : '');
        $list = $this->getOutTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 定义与发货单的多对多关联
    public function deliveries()
    {
        return $this->belongsToMany(
            'ClothmakingDelivery', // 关联模型
            'clothmakingOutstockDelivery', // 中间表
            'delivery_id', // 中间表关联发货单的字段
            'outstock_id' // 中间表关联出库单的字段
        );
    }

    // 定义关联关系
    public function product()
    {
        return $this->belongsTo('\app\admin\model\clothmaking_product\Index', 'product_id', 'id');
    }

    public function operator()
    {
        return $this->belongsTo('\app\admin\model\Admin', 'operator_id', 'id');
    }


    // 监听插入前事件
    protected static function init()
    {
        self::event('before_insert', function ($outstock) {
            self::checkStock($outstock);
        });

        self::event('before_update', function ($outstock) {
            //如果是超级管理员，则不阻止更新
            if (session('admin.id') == 1) {
                return;
            }

            // 如果状态是 completed，则阻止更新
            $originalStatus = self::where('id', $outstock->getData('id'))->value('status');
            if ($originalStatus === 'completed') {
                throw new \Exception('已完成的出库单无法修改');
                return;
            }
            self::checkStock($outstock);
        });

        // 监听删除前事件
        self::event('before_delete', function ($outstock) {
            $originalStatus = self::where('id', $outstock->getData('id'))->value('status');
            if ($originalStatus === 'completed') {
                throw new \Exception('已完成的出库单无法删除');
                return;
            }
        });

        self::event('after_insert', function ($outstock) {
            try {

                Db::startTrans();
                self::updateStock($outstock);
                Db::commit();
            } catch (Exception $e) {
                Log::error('Failed to update stock after insert: ' . $e->getMessage());
                Db::rollback();
                throw $e; // 抛出异常以便控制器或其他地方处理
            }
        });

        self::event('after_update', function ($outstock) {
            try {
                Db::startTrans();
                self::updateStock($outstock);
                Db::commit();
            } catch (Exception $e) {
                Log::error('Failed to update stock after update: ' . $e->getMessage());
                Db::rollback();
                throw $e; // 抛出异常以便控制器或其他地方处理
            }
        });
    }


    // 检查库存的方法
    private static function checkStock($outstock)
    {
        if ($outstock['status'] === 'checked') {
            $product = \app\admin\model\clothmaking_product\Index::get($outstock['product_id']);
            if (!$product) {
                throw new \Exception('产品不存在');
                return;
            }
            if ($product->stock < $outstock['quantity']) {
                throw new \Exception('出库数量大于库存数量');
            }
        }
    }

    // 更新库存的方法
    private static function updateStock($outstock)
    {
        if ($outstock['status'] === 'checked') {
            $product = \app\admin\model\clothmaking_product\Index::get($outstock['product_id']);
            if ($product) {
                $product->stock -= $outstock['quantity'];
                $product->save();
            }
        }
    }
}
